from django.contrib.auth.models import User

from django.db.models import Model, CharField, IntegerField, ForeignKey, DateField, DateTimeField, DecimalField, ManyToManyField, BooleanField

class _Named(Model):
   name = CharField(max_length=64, primary_key=True)
   def __unicode__(self):
      return u'%s' % (self.name)
   class Meta:
      abstract = True
      ordering = 'name',

class Creator(_Named):
   pass

class Ensemble(_Named):
   pass

class Genre(_Named):
   pass

class Year(_Named):
   pass

class Piece(Model):
   title = CharField(max_length=128)
   ensemble = ForeignKey (Ensemble,default='Unknown')
   genre = ForeignKey (Genre, default='Unknown')
   composer = ForeignKey (Creator, default='None', related_name='composer_rev')
   arranger = ForeignKey (Creator, default='None', related_name='arranger_rev')
   year = ForeignKey(Year, default='Unknown')
   notes = CharField(max_length=64, default='None')
   def __unicode__(self):
      return u'%s %s %s' % (self.title, self.composer, self.ensemble)
   class Meta:
      ordering = 'title',
      unique_together = 'title', 'composer', 'arranger', 'ensemble'

class Location(_Named):
   pass

class Part(_Named):
   pass

class LibraryPiece(Model):
   index = CharField (max_length=8, primary_key=True)
   piece = ForeignKey(Piece)
   location = ForeignKey (Location, default='Unknown')
   notes = CharField(max_length=128, null=True, blank=True)
   missing = ManyToManyField (Part, default='None')
   rating = IntegerField(default=0)
   order = IntegerField(default=0)
   flag = BooleanField()
   def __unicode__(self):
      return u'%s %s' % (self.index, self.piece)
   def lost(self):
      return ','.join([m.name for m in self.missing.all()])
   class Meta:
      ordering = 'piece__title',

class Programme(Model):
   notes = CharField(max_length=128)
   performances = ManyToManyField(LibraryPiece, through='Performance')
   class Meta:
      ordering = 'notes',
   def __unicode__(self):
      return u'%s' % self.notes 

class Performance(Model):
   piece = ForeignKey (LibraryPiece)
   concert = ForeignKey (Programme)
   order = IntegerField (default=0)
   class Meta:
      unique_together = 'piece', 'concert', 'order'
      ordering = 'order',
   def __unicode__(self):
      return u'%s %s' % (self.piece, self.concert)

class Band(_Named):
   register_date = DateField()
   expiry_date = DateField()
   user = ForeignKey(User)
   library = ManyToManyField(LibraryPiece)
   programmes = ManyToManyField(Programme)
